package com.datamanage.processing.service.impl;

import com.datamanage.processing.entity.ProcessingTask;
import com.datamanage.processing.dto.ProcessingTaskDTO;
import com.datamanage.processing.repository.ProcessingTaskRepository;
import com.datamanage.processing.service.ProcessingTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class ProcessingTaskServiceImpl implements ProcessingTaskService {
    
    @Autowired
    private ProcessingTaskRepository processingTaskRepository;
    
    @Override
    public ProcessingTask createTask(ProcessingTaskDTO taskDTO, Long userId, Long companyId) {
        ProcessingTask task = new ProcessingTask();
        task.setName(taskDTO.getName());
        task.setDescription(taskDTO.getDescription());
        task.setSourceDatasetId(taskDTO.getSourceDatasetId());
        task.setProcessingConfig(taskDTO.getProcessingConfig());
        task.setStatus("PENDING"); // 初始状态为待处理
        task.setProgress(0);
        task.setCreatedBy(userId);
        task.setCompanyId(companyId);
        task.setCreatedAt(LocalDateTime.now());
        task.setUpdatedAt(LocalDateTime.now());
        
        return processingTaskRepository.save(task);
    }
    
    @Override
    public Optional<ProcessingTask> getTaskById(Long id, Long companyId) {
        return processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId));
    }
    
    @Override
    public Page<ProcessingTask> getAllTasks(Long companyId, Pageable pageable) {
        return processingTaskRepository.findByCompanyId(companyId, pageable);
    }
    
    @Override
    public Page<ProcessingTask> getTasksByUserId(Long userId, Long companyId, Pageable pageable) {
        return processingTaskRepository.findByCompanyIdAndUserId(companyId, userId, pageable);
    }
    
    @Override
    public Page<ProcessingTask> getTasksByStatus(String status, Long companyId, Pageable pageable) {
        return processingTaskRepository.findByCompanyIdAndStatus(companyId, status, pageable);
    }
    
    @Override
    public ProcessingTask updateTask(Long id, ProcessingTaskDTO taskDTO, Long companyId) {
        ProcessingTask existingTask = processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId))
            .orElseThrow(() -> new RuntimeException("任务不存在或无权限访问"));
        
        // 只有在PENDING状态下才能更新任务配置
        if (!"PENDING".equals(existingTask.getStatus())) {
            throw new RuntimeException("只有待处理状态的任务才能更新配置");
        }
        
        existingTask.setName(taskDTO.getName());
        existingTask.setDescription(taskDTO.getDescription());
        existingTask.setSourceDatasetId(taskDTO.getSourceDatasetId());
        existingTask.setProcessingConfig(taskDTO.getProcessingConfig());
        existingTask.setUpdatedAt(LocalDateTime.now());
        
        return processingTaskRepository.save(existingTask);
    }
    
    @Override
    public void deleteTask(Long id, Long companyId) {
        ProcessingTask existingTask = processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId))
            .orElseThrow(() -> new RuntimeException("任务不存在或无权限访问"));
        
        // 只能删除已完成或失败的任务
        if (!("COMPLETED".equals(existingTask.getStatus()) || 
              "FAILED".equals(existingTask.getStatus()) ||
              "PENDING".equals(existingTask.getStatus()))) {
            throw new RuntimeException("只能删除待处理、已完成或失败的任务");
        }
        
        processingTaskRepository.deleteById(id);
    }
    
    @Override
    public ProcessingTask startTask(Long id, Long companyId) {
        ProcessingTask existingTask = processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId))
            .orElseThrow(() -> new RuntimeException("任务不存在或无权限访问"));
        
        // 只有待处理状态的任务才能启动
        if (!"PENDING".equals(existingTask.getStatus())) {
            throw new RuntimeException("只有待处理状态的任务才能启动");
        }
        
        existingTask.setStatus("RUNNING");
        existingTask.setStartedAt(LocalDateTime.now());
        existingTask.setProgress(0);
        existingTask.setUpdatedAt(LocalDateTime.now());
        
        return processingTaskRepository.save(existingTask);
    }
    
    @Override
    public ProcessingTask pauseTask(Long id, Long companyId) {
        ProcessingTask existingTask = processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId))
            .orElseThrow(() -> new RuntimeException("任务不存在或无权限访问"));
        
        // 只有运行中的任务才能暂停
        if (!"RUNNING".equals(existingTask.getStatus())) {
            throw new RuntimeException("只有运行中的任务才能暂停");
        }
        
        existingTask.setStatus("PAUSED");
        existingTask.setUpdatedAt(LocalDateTime.now());
        
        return processingTaskRepository.save(existingTask);
    }
    
    @Override
    public ProcessingTask resumeTask(Long id, Long companyId) {
        ProcessingTask existingTask = processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId))
            .orElseThrow(() -> new RuntimeException("任务不存在或无权限访问"));
        
        // 只有暂停的任务才能恢复
        if (!"PAUSED".equals(existingTask.getStatus())) {
            throw new RuntimeException("只有暂停的任务才能恢复");
        }
        
        existingTask.setStatus("RUNNING");
        existingTask.setUpdatedAt(LocalDateTime.now());
        
        return processingTaskRepository.save(existingTask);
    }
    
    @Override
    public ProcessingTask cancelTask(Long id, Long companyId) {
        ProcessingTask existingTask = processingTaskRepository.findById(id)
            .filter(task -> task.getCompanyId().equals(companyId))
            .orElseThrow(() -> new RuntimeException("任务不存在或无权限访问"));
        
        // 只有待处理、运行中或暂停的任务才能取消
        if (!("PENDING".equals(existingTask.getStatus()) || 
              "RUNNING".equals(existingTask.getStatus()) ||
              "PAUSED".equals(existingTask.getStatus()))) {
            throw new RuntimeException("只有待处理、运行中或暂停的任务才能取消");
        }
        
        existingTask.setStatus("FAILED");
        existingTask.setFailedAt(LocalDateTime.now());
        existingTask.setUpdatedAt(LocalDateTime.now());
        
        return processingTaskRepository.save(existingTask);
    }
}